﻿using Engine;
using Game;
using GameEntitySystem;
using SAGhoul.Blocks;
using SAGhoul.ParticleSystem;
using System;
using TemplatesDatabase;

namespace SAGhoul
{
	public class ComponentSAGhouls : Component, IUpdateable
	{
		public SubsystemCreatureSpawn m_subsystemCreatureSpawn;
		public SubsystemPlayers m_subsystemPlayers;
		public SubsystemProjectiles m_subsystemProjectiles;
		public SubsystemPickables m_subsystemPickables;
		public SubsystemAudio m_subsystemAudio;
		public SubsystemTerrain m_subsystemTerrain;
		public SubsystemSoundMaterials m_subsystemSoundMaterials;
		public SubsystemSAG m_subsystemSAG;
		public SubsystemExplosions m_subsystemExplosions;
		public SubsystemParticles m_subsystemParticles;
		public SubsystemTime m_subsystemTime;
		public SubsystemGameInfo m_subsystemGameInfo;
		public ComponentMiner m_componentMiner;
		public ComponentCreature m_componentCreature;
		public ComponentChaseBehavior m_componentChaseBehavior;
		public ComponentRunAwayBehavior m_componentRunAwayBehavior;
		public ComponentOnFire m_componentOnFire;

		public UpdateOrder UpdateOrder => UpdateOrder.Default;
		public Game.Random m_random = new();
		public Vector3 BoxSize;
		public float InAirWalkFactor;
		public string EntityName;

		public bool PersistentAttack;
		public bool IsTough;
		public bool KnockBackAttacking;
		public float ParryInterval;
		public int ShootValue;
		public float ShootInterval;
		public bool IsBoss;
		public float SkillRange;
		public bool AutoChaseSmallBrid;
		public bool DropItemInHand;
		private bool m_hasExploded = false;

		private float m_paryyCd;//期间禁用闪避的时间
		private float m_screamCd;
		public float m_digCd;
		public float m_fireCd;
		public float m_skillCd;
		public float m_hitByArtifactTime;
		public float m_skillProgress;

		public float m_chargeCd;
		public bool m_isCharging;
		public float m_chargeTime;

		public bool CanParry => ParryInterval > 0 && m_paryyCd <= 0 && m_componentCreature.ComponentBody.StandingOnValue.HasValue;//期间子弹攻击无效
		public bool Parrying
		{
			get => m_componentCreature.ComponentBody.BoxSize == new Vector3(0.0114514f);
			set
			{
				if (value)
					m_componentCreature.ComponentBody.BoxSize = new Vector3(0.0114514f);
				else
					m_componentCreature.ComponentBody.BoxSize = BoxSize;
			}
		}

		public float WalkSpeed, FlySpeed;
		public EliteParticleSystem m_eliteParticleSystem;
		public float m_injuryLimit;
		float m_skillRecoverFactor;
		bool m_lastIsCharging;
		bool m_initialized;
		ComponentPlayer necro_target;
		Quaternion necro_rotation;
		Vector2 necro_direction;
		float necro_time;
		float m_stuckTime;
		EggBlock.EggType eggType_SAGhoul_Ray, eggType_SAGhoul_Bird;

		public static float MaxInjury => 50f;

		public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
		{
			base.Load(valuesDictionary, idToEntityMap);
			m_subsystemCreatureSpawn = Project.FindSubsystem<SubsystemCreatureSpawn>(throwOnError: true);
			m_subsystemPlayers = Project.FindSubsystem<SubsystemPlayers>(throwOnError: true);
			m_subsystemProjectiles = Project.FindSubsystem<SubsystemProjectiles>(throwOnError: true);
			m_subsystemPickables = Project.FindSubsystem<SubsystemPickables>(throwOnError: true);
			m_subsystemAudio = Project.FindSubsystem<SubsystemAudio>(throwOnError: true);
			m_subsystemTerrain = Project.FindSubsystem<SubsystemTerrain>(throwOnError: true);
			m_subsystemSoundMaterials = Project.FindSubsystem<SubsystemSoundMaterials>(throwOnError: true);
			m_subsystemSAG = Project.FindSubsystem<SubsystemSAG>(throwOnError: true);
			m_subsystemExplosions = Project.FindSubsystem<SubsystemExplosions>(throwOnError: true);
			m_subsystemParticles = Project.FindSubsystem<SubsystemParticles>(throwOnError: true);
			m_subsystemTime = Project.FindSubsystem<SubsystemTime>(throwOnError: true);
			m_subsystemGameInfo = Project.FindSubsystem<SubsystemGameInfo>(throwOnError: true);
			m_componentChaseBehavior = Entity.FindComponent<ComponentChaseBehavior>();
			m_componentCreature = Entity.FindComponent<ComponentCreature>(throwOnError: true);
			m_componentRunAwayBehavior = Entity.FindComponent<ComponentRunAwayBehavior>();
			m_componentMiner = Entity.FindComponent<ComponentMiner>();
			m_componentOnFire = Entity.FindComponent<ComponentOnFire>();
			m_componentCreature.ComponentHealth.Injured += (injury) =>
			{
				ComponentCreature attacker = injury.Attacker;
				if (attacker != null)
					CallNearbyCreaturesHelp(attacker, 20f, 30f, isPersistent: false);
			};
			ValuesDictionary valuesDictionary1 = DatabaseManager.FindEntityValuesDictionary(Entity.ValuesDictionary.DatabaseObject.Name, throwIfNotFound: true);
			ValuesDictionary valuesDictionary_Loco = valuesDictionary1.GetValue<ValuesDictionary>("Locomotion");
			WalkSpeed = valuesDictionary_Loco.GetValue<float>("WalkSpeed");
			FlySpeed = valuesDictionary_Loco.GetValue<float>("FlySpeed");
			InAirWalkFactor = valuesDictionary_Loco.GetValue<float>("InAirWalkFactor");
			BoxSize = valuesDictionary1.GetValue<ValuesDictionary>("Body").GetValue<Vector3>("BoxSize");

			EntityName = Entity.ValuesDictionary.DatabaseObject.Name;
			PersistentAttack = valuesDictionary.GetValue<bool>("PersistentAttack");
			IsTough = valuesDictionary.GetValue<bool>("IsTough");
			KnockBackAttacking = valuesDictionary.GetValue<bool>("KnockBackAttacking");
			ParryInterval = valuesDictionary.GetValue<float>("ParryInterval");
			ShootValue = valuesDictionary.GetValue<int>("ShootValue");
			ShootInterval = valuesDictionary.GetValue<float>("ShootInterval");
			IsBoss = valuesDictionary.GetValue<bool>("IsBoss");
			SkillRange = valuesDictionary.GetValue<float>("SkillRange");
			AutoChaseSmallBrid = valuesDictionary.GetValue<bool>("AutoChaseSmallBrid");
			DropItemInHand = valuesDictionary.GetValue<bool>("DropItemInHand");
			m_digCd = valuesDictionary.GetValue<float>("DigCd");
			m_skillCd = valuesDictionary.GetValue<float>("SkillCd");
			m_skillRecoverFactor = m_random.Float(0.8f, 1.1f);
			m_chargeCd = valuesDictionary.GetValue<float>("ChargeCd", 30f);
			necro_rotation = valuesDictionary.GetValue<Quaternion>("NecroRotation", Quaternion.Identity).FixNaN();
			necro_direction = valuesDictionary.GetValue<Vector2>("NecroDirection", Vector2.Zero);
			necro_time = valuesDictionary.GetValue<float>("NecroTime", 0f);
			eggType_SAGhoul_Ray = ((EggBlock)BlocksManager.Blocks[EggBlock.Index]).GetEggTypeByCreatureTemplateName("SAGhoul_Ray");
			eggType_SAGhoul_Bird = ((EggBlock)BlocksManager.Blocks[EggBlock.Index]).GetEggTypeByCreatureTemplateName("SAGhoul_Bird");
			m_initialized = false;
		}

		public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
		{
			base.Save(valuesDictionary, entityToIdMap);
			valuesDictionary.SetValue("PersistentAttack", PersistentAttack);
			valuesDictionary.SetValue("DigCd", m_digCd);
			valuesDictionary.SetValue("SkillCd", m_skillCd);
			valuesDictionary.SetValue("IsBoss", IsBoss);
			valuesDictionary.SetValue("NecroRotation", necro_rotation);
			valuesDictionary.SetValue("NecroDirection", necro_direction);
			valuesDictionary.SetValue("NecroTime", necro_time);
		}
		public void Initialize()
		{
			if (EntityName == "SAGhoul_Strong_07" || EntityName == "SAGhoul_Strong_08")
			{//随机初始武器
				var inventory = Entity.FindComponent<ComponentInventory>(throwOnError: false);
				if (inventory != null && (Terrain.ExtractContents(inventory.GetSlotValue(inventory.ActiveSlotIndex)) == 0 || inventory.GetSlotCount(inventory.ActiveSlotIndex) <= 0))
				{
					inventory.AddSlotItems(inventory.ActiveSlotIndex, m_random.Bool()
						? typeof(MultipleSpearBlock).BlockIndex()
						: typeof(SplittingSpearBlock).BlockIndex(), 1);
				}
			}
			m_initialized = true;
		}
		public void Update(float dt)
		{
			if (!m_initialized)
				Initialize();
			if (m_componentCreature.ComponentHealth.Health <= 0)
			{
				if (EntityName == "SAGhoul_Fatt")
				{//自爆
					ComponentBody componentBody = m_componentCreature.ComponentBody;
					ComponentCreature target = m_componentChaseBehavior?.Target;
					ComponentLoot componentLoot = Entity.FindComponent<ComponentLoot>();
					bool onFire = m_componentCreature.Entity.FindComponent<ComponentOnFire>()?.IsOnFire ?? false;
					var list = onFire ? componentLoot.m_lootOnFireList : componentLoot.m_lootList;
					Vector3 dropPosition = (m_componentCreature.ComponentBody.BoundingBox.Min + m_componentCreature.ComponentBody.BoundingBox.Max) / 2f;
					Point3 point = Terrain.ToCell(componentBody.BoundingBox.Center());
					Project.RemoveEntity(Entity, true);
					m_subsystemExplosions.AddExplosion(point.X, point.Y, point.Z, 200f, true, false);
					Time.QueueTimeDelayedExecution(Time.FrameStartTime + 0.5, delegate
					{
						foreach (ComponentLoot.Loot item in list)
						{
							if (m_random.Float(0f, 1f) < item.Probability)
							{
								int num2 = m_random.Int(item.MinCount, item.MaxCount);
								for (int i = 0; i < num2; i++)
								{
									m_subsystemPickables.AddPickable(item.Value, 1, dropPosition, null, null);
								}
							}
						}
						for (int i = 0; i < m_random.Int(5, 7); i++)
						{
							Entity entity = DatabaseManager.CreateEntity(Project, "SAGhoul_Bird", throwIfNotFound: true);
							ComponentBody body = entity.FindComponent<ComponentBody>(throwOnError: true);
							body.Position = componentBody.BoundingBox.Center() + m_random.Vector3(0f, 0.5f);
							body.Rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitY, m_random.Float(0f, (float)Math.PI * 2f));
							entity.FindComponent<ComponentSpawn>(throwOnError: true).SpawnDuration = 0.25f;
							ComponentChaseBehavior componentChaseBehavior = entity.FindComponent<ComponentChaseBehavior>();
							componentChaseBehavior?.Attack(target, 50f, 60f, true);
							Project.AddEntity(entity);
						}
					});
				}

				if (EntityName == "SAGhoul_Wolf")
				{//变异狼分裂行为
					ComponentBody componentBody = m_componentCreature.ComponentBody;
					ComponentCreature target = m_componentChaseBehavior?.Target;
					ComponentLoot componentLoot = Entity.FindComponent<ComponentLoot>();
					bool onFire = m_componentCreature.Entity.FindComponent<ComponentOnFire>()?.IsOnFire ?? false;
					var list = onFire ? componentLoot.m_lootOnFireList : componentLoot.m_lootList;
					Vector3 dropPosition = (m_componentCreature.ComponentBody.BoundingBox.Min + m_componentCreature.ComponentBody.BoundingBox.Max) / 2f;

					Project.RemoveEntity(Entity, true);

					Time.QueueTimeDelayedExecution(Time.FrameStartTime + 0.5, delegate
					{
						foreach (ComponentLoot.Loot item in list)
						{
							if (m_random.Float(0f, 1f) < item.Probability)
							{
								int num2 = m_random.Int(item.MinCount, item.MaxCount);
								for (int i = 0; i < num2; i++)
								{
									m_subsystemPickables.AddPickable(item.Value, 1, dropPosition, null, null);
								}
							}
						}

						// Spawn exactly 3 Dogs
						for (int i = 0; i < 3; i++)
						{
							Entity entity = DatabaseManager.CreateEntity(Project, "SAGhoul_Dog", throwIfNotFound: true);
							ComponentBody body = entity.FindComponent<ComponentBody>(throwOnError: true);
							body.Position = componentBody.BoundingBox.Center() + m_random.Vector3(0f, 0.5f);
							body.Rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitY, m_random.Float(0f, (float)Math.PI * 2f));
							entity.FindComponent<ComponentSpawn>(throwOnError: true).SpawnDuration = 0.25f;
							ComponentChaseBehavior componentChaseBehavior = entity.FindComponent<ComponentChaseBehavior>();
							componentChaseBehavior?.Attack(target, 50f, 60f, true);
							Project.AddEntity(entity);
						}
						m_subsystemAudio.PlaySound("Audio/Creatures/Ghouls_Wolf/Fenglie", 3f, m_random.Float(-0.2f, 0.2f), SkillRange, 0f);
					});
				}
				if (EntityName == "SAGhoul_Strong_06")
				{
					// 获取组件和状态
					ComponentBody componentBody = m_componentCreature.ComponentBody;
					ComponentCreature target = m_componentChaseBehavior?.Target;
					ComponentLoot componentLoot = Entity.FindComponent<ComponentLoot>();
					bool onFire = m_componentCreature.Entity.FindComponent<ComponentOnFire>()?.IsOnFire ?? false;

					// 准备战利品列表和位置
					var list = onFire ? componentLoot.m_lootOnFireList : componentLoot.m_lootList;
					Vector3 dropPosition = (m_componentCreature.ComponentBody.BoundingBox.Min + m_componentCreature.ComponentBody.BoundingBox.Max) / 2f;
					Point3 explosionPoint = Terrain.ToCell(componentBody.BoundingBox.Center());

					// 2. 检查是否已经爆炸过（防御性编程）
					if (!m_hasExploded) // 确保 m_hasExploded 是类成员变量（private bool m_hasExploded = false;）
					{
						m_hasExploded = true; // 立即标记为已爆炸，防止重复触发

						m_subsystemAudio.PlaySound("Audio/Creatures/Ghouls/GhoulBomm/C4", 4f, 0f, componentBody.Position, 2f, false);

						// 3. 延时3秒执行爆炸和移除
						Time.QueueTimeDelayedExecution(Time.FrameStartTime + 2.5, delegate
						{
							// 先移除实体（避免爆炸后残留）
							Project.RemoveEntity(Entity, true);

							// 再触发爆炸（确保只执行一次）
							m_subsystemExplosions.AddExplosion(
								explosionPoint.X,
								explosionPoint.Y,
								explosionPoint.Z,
								60f,  // 爆炸强度
								true, // 是否引发火灾
								false //是否静音
							);
						});
					}
				}
				if (m_lastIsCharging)
				{
					m_subsystemSAG.SkyColorFactor = 0f;
					m_lastIsCharging = false;
				}
				return;
			}
			m_paryyCd = MathUtils.Max(m_paryyCd - dt, 0);
			m_screamCd = MathUtils.Max(m_screamCd - dt, 0);
			m_digCd = MathUtils.Max(m_digCd - dt, 0);
			m_fireCd = MathUtils.Max(m_fireCd - dt, 0);
			m_skillCd = MathUtils.Max(m_skillCd - dt * m_skillRecoverFactor, 0);
			m_hitByArtifactTime = MathUtils.Max(m_hitByArtifactTime - dt, 0);
			bool noSurvivePlayerRound = false;
			if (PersistentAttack)
			{//持续追击玩家
				if (!SAGhoulsManager.IsDuringBloodMoon(m_subsystemSAG) && !IsBoss)
				{
					PersistentAttack = false;
				}
				else if (m_componentChaseBehavior != null)
				{
					if (m_componentChaseBehavior.Target == null)
					{
						noSurvivePlayerRound = true;
						foreach (var player in m_subsystemPlayers.ComponentPlayers)
						{
							float distanceSqu = Vector2.DistanceSquared(player.ComponentBody.Position.XZ, m_componentCreature.ComponentBody.Position.XZ);
							if (distanceSqu <= 2500)//50*50=2500
							{
								noSurvivePlayerRound = false;
								m_componentChaseBehavior.Attack(player.ComponentMiner.ComponentCreature, 50f, float.MaxValue, true);
								break;
							}
						}
					}
				}
				else
					noSurvivePlayerRound = true;
			}
			else if (AutoChaseSmallBrid && m_componentChaseBehavior != null && m_componentChaseBehavior.Target == null && m_subsystemTime.PeriodicGameTimeEvent(5, 0))
			{//空闲时清理附近的小鸟
				foreach (ComponentCreature creature in m_subsystemCreatureSpawn.Creatures)
				{
					if (Vector3.DistanceSquared(m_componentCreature.ComponentBody.Position, creature.ComponentBody.Position) < 144f)//12*12=144
					{
						string entityName = creature.Entity.ValuesDictionary.DatabaseObject.Name;
						if (entityName == "Pigeon" || entityName == "Sparrow")
							m_componentChaseBehavior.Attack(creature, 20f, 60f, false);
					}
				}
			}
			if (noSurvivePlayerRound)
				PersistentAttack = false;
			if (m_componentRunAwayBehavior != null)
			{//禁用逃跑行为
				m_componentRunAwayBehavior.m_timeToForgetAttacker = 0;
				m_componentRunAwayBehavior.m_attacker = null;
				m_componentRunAwayBehavior.m_importanceLevel = 0;
				m_componentRunAwayBehavior.m_heardNoise = false;
				m_componentRunAwayBehavior.m_lastNoiseSourcePosition = null;
			}
			if (CanParry && m_skillProgress <= 0)
			{//躲避远程攻击
				foreach (var item in m_subsystemProjectiles.Projectiles)
				{
					Vector3 position = item.Position;
					if (Vector3.DistanceSquared(position, m_componentCreature.ComponentBody.Position) <= 100)//10*10=100
					{
						Vector3 v = m_componentCreature.ComponentBody.Position - position;
						float angle = SAGhoulsManager.GetAngleByVector(item.Velocity, v);
						if (angle <= MathUtils.DegToRad(45f))
						{
							Vector3 direction = Vector3.Normalize(Vector3.Cross(Vector3.UnitY, v)) * (m_random.Bool() ? -0.5f : 0.5f);
							Parry(direction);
							if (item.Owner != null && m_componentChaseBehavior != null && item.Owner.Entity.FindComponent<ComponentSAGhouls>() == null)
							{
								m_componentChaseBehavior.Attack(item.Owner, 30f, 60f, isPersistent: true);
							}
							break;
						}
					}
				}
			}
			if (m_componentCreature.ComponentLocomotion.LadderSpeed > 0f && m_componentCreature.ComponentBody.ParentBody == null)
			{//爬墙
				Vector3 startPosition = m_componentCreature.ComponentBody.Position;
				var raycast = m_subsystemTerrain.Raycast(startPosition, startPosition + Vector3.Normalize(m_componentCreature.ComponentBody.Matrix.Forward), useInteractionBoxes: false, skipAirBlocks: true, (value, distance) => BlocksManager.Blocks[Terrain.ExtractContents(value)].IsCollidable_(value));
				if (raycast.HasValue)
				{
					CellFace cellFace = raycast.Value.CellFace;
					int cellValue = m_subsystemTerrain.Terrain.GetCellValue(cellFace.X, cellFace.Y, cellFace.Z);
					int num = Terrain.ExtractContents(cellValue);
					Block block = BlocksManager.Blocks[num];
					int face = cellFace.Face;
					if (face == 0 && m_componentCreature.ComponentBody.CollisionVelocityChange.Z > 0f || face == 1 && m_componentCreature.ComponentBody.CollisionVelocityChange.X > 0f || face == 2 && m_componentCreature.ComponentBody.CollisionVelocityChange.Z < 0f || face == 3 && m_componentCreature.ComponentBody.CollisionVelocityChange.X < 0f || !m_componentCreature.ComponentBody.StandingOnValue.HasValue)
					{
						Vector3 position = m_componentCreature.ComponentBody.Position;
						Vector3 velocity = m_componentCreature.ComponentBody.Velocity;
						m_componentCreature.ComponentCreatureSounds.PlayFootstepSound(1f);
						Vector2 value2 = Vector2.One;// m_componentCreature.ComponentLocomotion.WalkOrder.Value;
						float num2 = m_componentCreature.ComponentLocomotion.LadderSpeed * value2.Y;
						velocity.Y += MathUtils.Saturate(20f * dt) * (num2 - velocity.Y);
						Vector2? jumpBackOrder = null;
						if (m_componentChaseBehavior != null && m_componentChaseBehavior.Target != null && position.Y - m_componentChaseBehavior.Target.ComponentBody.Position.Y > 3f)
						{
							Vector3 targetCenter = m_componentChaseBehavior.Target.ComponentBody.BoundingBox.Center();
							Vector3 direciton = targetCenter - m_componentCreature.ComponentBody.BoundingBox.Center();
							float angle = SAGhoulsManager.GetAngleByVector(direciton.XZ, -m_componentCreature.ComponentBody.Matrix.Forward.XZ);
							if (angle <= MathUtils.DegToRad(60f))
								jumpBackOrder = targetCenter.XZ;
						}
						if (jumpBackOrder.HasValue)
						{
							m_componentCreature.ComponentCreatureSounds.PlayFootstepSound(2f);
							Vector2 v = Vector2.Normalize(jumpBackOrder.Value - position.XZ) * MathUtils.Min(10f, Vector2.Distance(jumpBackOrder.Value, position.XZ));
							velocity = new Vector3(v.X, 1f, v.Y);
							if (m_screamCd <= 0)
							{
								m_subsystemAudio.PlayRandomSound("Audio/Creatures/Ghoul_Monster/Scream", 0.5f, m_random.Float(-0.25f, 0f), m_componentCreature.ComponentBody.Position, 32f, autoDelay: true);
								m_screamCd = 1.5f;
							}
						}
						m_componentCreature.ComponentBody.Velocity = velocity;
					}
				}
			}
			if (m_screamCd <= 0 && EntityName == "SAGhoul_Monster" && m_componentCreature.ComponentLocomotion.LastJumpOrder >= 1f && m_componentCreature.ComponentLocomotion.JumpOrder <= 0f && m_random.Bool(0.25f))
			{//发出尖啸
				if (m_componentChaseBehavior != null && m_componentChaseBehavior.Target != null && Vector3.DistanceSquared(m_componentCreature.ComponentBody.Position, m_componentChaseBehavior.Target.ComponentBody.Position) <= 36f)//6*6=36
				{
					m_subsystemAudio.PlayRandomSound("Audio/Creatures/Ghoul_Monster/Scream", 0.5f, m_random.Float(-0.25f, 0f), m_componentCreature.ComponentBody.Position, 32f, autoDelay: true);
					m_screamCd = 1.5f;
				}
			}
			if (m_componentMiner != null && m_componentChaseBehavior != null && m_componentChaseBehavior.Target != null)
			{//破坏方块
				int slotValue = m_componentMiner.ActiveBlockValue, id = Terrain.ExtractContents(slotValue);
				if (id > 0 && m_digCd <= 0)
				{//手持工具
					Vector3 eyePosition = m_componentCreature.ComponentCreatureModel.EyePosition;
					Vector3 direction = Vector3.Normalize(m_componentChaseBehavior.Target.ComponentBody.BoundingBox.Center() - eyePosition);
					Block block = BlocksManager.Blocks[id];
					float quarryPower = block.GetQuarryPower(slotValue);//镐
					float hackPower = block.GetHackPower(slotValue);//斧
					float shovelPower = block.GetShovelPower(slotValue);//铲
					float rate = 10;
					TerrainRaycastResult? raycastResult = null;
					TerrainRaycastResult? terrainRaycastResult = m_subsystemTerrain.Raycast(eyePosition, eyePosition + direction * 1.5f, false, true, delegate (int value, float distance)
					{
						return IsDigable(value, ref rate, quarryPower, hackPower, shovelPower);
					});
					if (terrainRaycastResult.HasValue)
						raycastResult = terrainRaycastResult.Value;
					else
					{
						direction = Vector3.Normalize(m_componentChaseBehavior.Target.ComponentBody.BoundingBox.Center() - m_componentCreature.ComponentBody.Position);
						raycastResult = m_subsystemTerrain.Raycast(m_componentCreature.ComponentBody.Position, m_componentCreature.ComponentBody.Position + direction * 1.5f, false, true, delegate (int value, float distance)
						{
							return IsDigable(value, ref rate, quarryPower, hackPower, shovelPower);
						});
					}
					if (raycastResult.HasValue && rate > 0)
					{
						Dig(raycastResult.Value, slotValue);
						m_subsystemAudio.PlaySound("Audio/Spikes", 2f, m_random.Float(-0.1f, 0.1f), eyePosition, 40f, true);
						m_digCd = rate * 100f;
					}
				}
			}
			if (ShootValue > 0 && m_fireCd <= 0 && m_componentChaseBehavior != null && m_componentChaseBehavior.Target != null)
			{
				// 计算与目标的距离平方（优化性能，避免开平方运算）
				// 10*10=100表示最小攻击距离为10个单位
				bool inRange = Vector3.DistanceSquared(m_componentCreature.ComponentBody.Position, m_componentChaseBehavior.Target.ComponentBody.Position) >= 100f;

				if (inRange)
				{
					// 获取生物模型组件用于动画控制
					ComponentCreatureModel creatureModel = m_componentCreature.ComponentCreatureModel;

					// 播放投掷动画 - 右手上抬180度（1.8弧度≈180度）
					if (creatureModel != null)
					{
						// 设置右手臂的旋转角度（X轴旋转1.8弧度）
						((ComponentHumanModel)creatureModel).m_handAngles2 = new Vector2(1.8f, 0);
					}

					// 准备发射参数
					Vector3 eyePosition = m_componentCreature.ComponentCreatureModel.EyePosition; // 从眼睛位置发射
					Vector3 direction = Vector3.Normalize(m_componentChaseBehavior.Target.ComponentBody.BoundingBox.Center() - eyePosition);
					// 从方块数据中获取抛射物速度
					float speed = BlocksManager.Blocks[Terrain.ExtractContents(ShootValue)].ProjectileSpeed;

					// 发射第一个抛射物
					// 速度 = 基础速度 * (方向 + 头部抖动偏移) + 垂直方向上的抛物线初速度
					Vector3 velocity1 = speed * (direction + new Vector3(m_componentCreature.ComponentCreatureModel.HeadShakeOrder)) + Vector3.UnitY * MathUtils.Pow(1.8f, 2) * 2f;
					Projectile projectile1 = m_subsystemProjectiles.FireProjectile(ShootValue, eyePosition, velocity1, m_random.Vector3(2f, 4f), m_componentCreature);

					if (projectile1 != null)
					{
						projectile1.ProjectileStoppedAction = ProjectileStoppedAction.Disappear; // 碰到物体后消失
						projectile1.TrailParticleSystem = new PukeTrailParticleSystem(10, 0.75f, float.MaxValue, Color.LightBlue); // 蓝色尾迹粒子
						projectile1.TrailOffset = Vector3.Zero; // 尾迹位置偏移
					}

					// 发射第二个抛射物（方向略有不同）
					Vector3 velocity2 = speed * (direction + new Vector3(m_componentCreature.ComponentCreatureModel.HeadShakeOrder) + new Vector3(0.1f, 0, 0.1f)) + Vector3.UnitY * MathUtils.Pow(1.9f, 2) * 2f;
					Projectile projectile2 = m_subsystemProjectiles.FireProjectile(ShootValue, eyePosition, velocity2, m_random.Vector3(2f, 4f), m_componentCreature);

					if (projectile2 != null)
					{
						projectile2.ProjectileStoppedAction = ProjectileStoppedAction.Disappear;
						projectile2.TrailParticleSystem = new PukeTrailParticleSystem(10, 0.75f, float.MaxValue, Color.LightBlue);
						projectile2.TrailOffset = Vector3.Zero;
					}

					// 播放射击音效
					m_subsystemAudio.PlaySound("Audio/DispenserShoot", 1f, 0f, eyePosition, 4f, autoDelay: true);
					// 设置攻击冷却时间（至少0.05秒）
					m_fireCd = MathUtils.Max(0.05f, ShootInterval);
				}
			}

			if (m_fireCd <= 0 && EntityName == "SAGhoul_Fatt" && m_componentChaseBehavior != null && m_componentChaseBehavior.Target != null)
			{//远程攻击2
				bool inRange = Vector3.DistanceSquared(m_componentCreature.ComponentBody.Position, m_componentChaseBehavior.Target.ComponentBody.Position) >= 225f;//15*15=100
				if (inRange)
				{
					Vector3 eyePosition = m_componentCreature.ComponentCreatureModel.EyePosition;
					Vector3 direction = Vector3.Normalize(m_componentChaseBehavior.Target.ComponentBody.BoundingBox.Center() - eyePosition);
					float speed = BlocksManager.Blocks[Terrain.ExtractContents(105)].ProjectileSpeed;
					Vector3 velocity = speed * direction * 8f;  // 8倍基础速度增强
					velocity += direction * MathUtils.Pow(3.2f, 2);  // 附加强力前冲
					velocity += Vector3.UnitY * 18f;  // 大幅度上扬(迫击炮弹道)
					Projectile projectile = m_subsystemProjectiles.FireProjectile(SnowballBlock.Index, eyePosition, velocity, m_random.Vector3(2f, 4f), m_componentCreature);
					if (projectile != null)
					{
						projectile.ProjectileStoppedAction = ProjectileStoppedAction.Disappear;
						projectile.TrailParticleSystem = new PukeTrailParticleSystem(10, 0.75f, float.MaxValue, Color.LightRed);
						projectile.TrailOffset = Vector3.Zero;
					}
					m_subsystemAudio.PlaySound("Audio/Creatures/Ghouls_Fatt/TD/DF41", 3f, m_random.Float(-0.2f, 0.2f), SkillRange, 0f);
					m_fireCd = 6f;
				}
			}
			float speedLimit = 1f;
			if (EntityName == "SAGhoul_Ray" && m_componentChaseBehavior?.Target != null && (m_componentChaseBehavior?.Target?.IsAddedToProject ?? false) && m_componentChaseBehavior?.Target?.ComponentHealth?.Health > 0f)
			{
				var flyOrder = m_componentCreature.ComponentLocomotion.FlyOrder.HasValue
					? new Vector3(m_componentCreature.ComponentLocomotion.FlyOrder.Value.X, m_componentCreature.ComponentLocomotion.FlyOrder.Value.Y, m_componentCreature.ComponentLocomotion.FlyOrder.Value.Z)
					: Vector3.Zero;
				var position = m_componentCreature.ComponentBody.Position;
				var targetPosition = m_componentChaseBehavior.Target.ComponentBody.BoundingBox.Center();
				var distanceSquared = Vector3.DistanceSquared(position, targetPosition);
				if (position.Y < targetPosition.Y + 4f)//保持位置比攻击目标高4格
					flyOrder.Y = MathUtils.Max(flyOrder.Y, 1f);
				else//如果高才禁用飞行，避免在地上不动
					speedLimit = MathUtils.Lerp(float.Epsilon, 1f, MathUtils.Saturate(distanceSquared - MathUtils.Sqr(7.5f)));//距离小于7.5时停止移动
				m_componentCreature.ComponentLocomotion.FlyOrder = flyOrder;
				if (m_fireCd <= 0f)
				{//发射追踪灵魂块
					SAGProjectile projectile = m_subsystemProjectiles.FireProjectile<SAGProjectile>(typeof(LargeSoulsResidueBlock).BlockIndex(), position, -Vector3.UnitY, m_random.Vector3(2f, 4f), m_componentCreature);
					if (projectile != null)
					{
						projectile.ProjectileStoppedAction = ProjectileStoppedAction.Disappear;
						projectile.TrailParticleSystem = new PukeTrailParticleSystem(10, 0.75f, float.MaxValue, Color.Purple);
						projectile.TrailOffset = Vector3.Zero;
						projectile.Target = m_componentChaseBehavior.Target;
					}
					m_subsystemAudio.PlayRandomSound("Audio/BossSkills/ParticleAttack", 2.5f, m_random.Float(-0.2f, 0.2f), position, SkillRange, 0f);
					m_fireCd = 4f;
				}
			}
			if (EntityName == "SAGhoul_NecroDrift")
				UpdateNecro(dt);
			m_componentCreature.ComponentLocomotion.FlySpeed = FlySpeed * speedLimit;
			bool charging = false;
			if (IsBoss)
			{//boss粒子
				BoundingBox boundingBox = m_componentCreature.ComponentBody.BoundingBox;
				Vector3 particlePosition = 0.5f * (boundingBox.Min + boundingBox.Max);
				float particleRadius = 1.2f;
				if (EntityName.Contains("Dark"))
				{//dark特殊机制
					float speed = m_componentCreature.ComponentBody.Velocity.Length();
					if (speed >= 0.1)//0.9-3.4
					{//走路造成屏幕摇晃
						foreach (var player in m_subsystemPlayers.ComponentPlayers)
						{
							float distanceSquared = Vector3.DistanceSquared(m_componentCreature.ComponentBody.Position, player.ComponentBody.Position);
							if (distanceSquared <= 225f && SAGhoulsManager.IsOnGround(player.ComponentBody))
							{
								ComponentSAGPlayer componentSAGPlayer = player.Entity.FindComponent<ComponentSAGPlayer>();
								if (componentSAGPlayer != null && componentSAGPlayer.ExplodeSwayT <= 0)
								{
									componentSAGPlayer.ExplodeSwayT = 0.25f;
									componentSAGPlayer.ExplodeSwayPower = 3f;
								}
							}
						}
					}
					var target = m_componentChaseBehavior.Target;
					if (target != null)
					{
						float distanceSquared = Vector3.DistanceSquared(target.ComponentBody.Position, boundingBox.Center());
						float distanceSquared2 = Vector3.DistanceSquared(target.ComponentBody.BoundingBox.Center(), m_componentCreature.ComponentBody.Position);
						if (m_componentChaseBehavior.m_componentPathfinding.m_stateMachine.CurrentState != "MovingDirect" && (distanceSquared <= MathUtils.Sqr(5f) || distanceSquared2 <= MathUtils.Sqr(5f)))
							m_stuckTime = MathUtils.Min(5f, m_stuckTime + dt);
						else
							m_stuckTime = MathUtils.Max(0f, m_stuckTime - dt);
						bool isStuck = m_stuckTime >= 2f;//制裁修脚
						bool flag = isStuck && (distanceSquared <= MathUtils.Sqr(5f) || distanceSquared2 <= MathUtils.Sqr(5f));
						if ((distanceSquared <= MathUtils.Sqr(4f) || distanceSquared2 <= MathUtils.Sqr(4f) || flag) && m_subsystemTime.PeriodicGameTimeEvent(isStuck ? 0.33 : 3, 0))
						{//环绕粒子攻击贴近目标
							Vector3 start = m_componentCreature.ComponentCreatureModel.EyePosition, end = target.ComponentBody.BoundingBox.Center();
							var particle = new SoulsAttackParticleSystem(start, end, 1f);
							m_subsystemParticles.AddParticleSystem(particle);
							m_subsystemAudio.PlayRandomSound("Audio/BossSkills/ParticleAttack", 2f, m_random.Float(-0.2f, 0.2f), boundingBox.Center(), SkillRange, 0f);
							target.ComponentHealth.Injure(0.1f, m_componentCreature, false, this.Lang("SoulShock"));
							target.ComponentBody.ApplyImpulse(10f * Vector3.Normalize(target.ComponentBody.Position - m_componentCreature.ComponentBody.Position + Vector3.UnitY));
						}
						if (m_skillCd <= 0 && (distanceSquared >= 25f || m_skillProgress > 0))
						{//boss技能攻击
							if (m_skillProgress <= 0)
							{
								//m_subsystemAudio.PlayRandomSound("Audio/ThunderFar", 4f, m_random.Float(-0.2f, 0.2f), boundingBox.Center(), SkillRange, 0f);
								m_subsystemAudio.PlayRandomSound("Audio/BossSkills/Skill_Ready", 3f, m_random.Float(-0.2f, 0.2f), boundingBox.Center(), SkillRange, 0f);
							}
							if (m_subsystemTime.PeriodicGameTimeEvent(1, 0))
							{
								m_componentCreature.ComponentCreatureSounds.PlayPainSound();
								if (m_skillProgress >= 0.6f)
									m_subsystemSAG.SkyBrightness = 1f;
							}
							m_skillProgress += 0.33f * dt;//蓄力
							particlePosition = m_componentCreature.ComponentCreatureModel.EyePosition;
							particleRadius = m_skillProgress * 10f;
							m_componentCreature.ComponentCreatureModel.AimHandAngleOrder = 3.2f;
							m_componentCreature.ComponentLocomotion.WalkSpeed = 0f;
							if (m_skillProgress >= 1f)
							{
								SAGhoulsManager.SoulsAttack(target, m_componentCreature);
								m_subsystemAudio.PlayRandomSound("Audio/BossSkills/Skill_Release", 3f, m_random.Float(-0.2f, 0.2f), boundingBox.Center(), SkillRange, 0f);

								m_skillProgress = 0;
								m_skillCd = 12f;
							}
							m_subsystemSAG.SkyColorFactor = m_skillProgress;
							charging = true;
						}
					}
				}
				if (m_eliteParticleSystem == null)
				{//boss粒子
					m_eliteParticleSystem = new EliteParticleSystem();
					m_subsystemParticles.AddParticleSystem(m_eliteParticleSystem);
				}
				m_eliteParticleSystem.Position = particlePosition;
				m_eliteParticleSystem.Radius = particleRadius * MathUtils.Min(boundingBox.Max.X - boundingBox.Min.X, boundingBox.Max.Z - boundingBox.Min.Z);
			}
			else
			{
				if (m_eliteParticleSystem != null)
				{
					m_eliteParticleSystem.IsStopped = true;
					m_eliteParticleSystem = null;
				}
			}

			if (!charging)
			{
				m_componentCreature.ComponentLocomotion.WalkSpeed = WalkSpeed;
				m_skillProgress = 0;
				if (m_lastIsCharging)
				{
					m_subsystemSAG.SkyColorFactor = 0;
				}
			}
			m_lastIsCharging = charging;

			if (m_hitByArtifactTime > 0)
			{
				m_componentCreature.ComponentLocomotion.StunTime = m_hitByArtifactTime;
			}
			else if (IsTough)//如果坚韧，清除硬直时间
				m_componentCreature.ComponentLocomotion.StunTime = 0;
			if (m_subsystemTime.PeriodicGameTimeEvent(1, 0))
			{//每隔一秒，清除一次伤害限制累计
				m_injuryLimit = 0;
			}
		}
		public void Parry(Vector3 direction)
		{
			m_componentCreature.ComponentBody.Velocity = direction * 8f + 3f * Vector3.UnitY;
			m_subsystemAudio.PlayRandomSound("Audio/Creatures/Ghoul_Monster/Parry", 1f, m_random.Float(-0.25f, 0f), m_componentCreature.ComponentBody.Position, 3f, autoDelay: true);

			Parrying = true;
			m_componentCreature.ComponentLocomotion.InAirWalkFactor = 0;
			Time.QueueTimeDelayedExecution(Time.FrameStartTime + 0.9, delegate
			{
				Parrying = false;
				m_componentCreature.ComponentLocomotion.InAirWalkFactor = InAirWalkFactor;
			});
			float num = ParryInterval;
			if (m_componentOnFire != null && m_componentOnFire.IsOnFire)
				num *= 2f;//着火时2倍冷却时间
			m_paryyCd = num;
		}
		public void CallNearbyCreaturesHelp(ComponentCreature target, float maxRange, float maxChaseTime, bool isPersistent)
		{
			Vector3 position = target.ComponentBody.Position;
			foreach (ComponentCreature creature in m_subsystemCreatureSpawn.Creatures)
			{
				if (Vector3.DistanceSquared(position, creature.ComponentBody.Position) < 576f)//24*24=576
				{
					ComponentSAGhouls componentSAGhouls = creature.Entity.FindComponent<ComponentSAGhouls>();
					if (componentSAGhouls != null)// && componentSAGhouls.HerdName == HerdName && componentSAGhouls.m_autoNearbyCreaturesHelp)
					{
						ComponentChaseBehavior componentChaseBehavior = creature.Entity.FindComponent<ComponentChaseBehavior>();
						if (componentChaseBehavior != null && componentChaseBehavior.Target == null)
						{
							componentChaseBehavior.Attack(target, maxRange, maxChaseTime, isPersistent);
						}
					}
				}
			}
		}

		public void Dig(TerrainRaycastResult raycastResult, int activeBlockValue)
		{
			CellFace cellFace = raycastResult.CellFace;
			int cellValue = m_subsystemTerrain.Terrain.GetCellValue(cellFace.X, cellFace.Y, cellFace.Z);
			int num = Terrain.ExtractContents(cellValue);
			Block block = BlocksManager.Blocks[num];
			int num2 = Terrain.ExtractContents(activeBlockValue);
			Block block2 = BlocksManager.Blocks[num2];
			BlockPlacementData digValue = block.GetDigValue(m_subsystemTerrain, m_componentMiner, cellValue, activeBlockValue, raycastResult);
			m_subsystemTerrain.DestroyCell(block2.ToolLevel, digValue.CellFace.X, digValue.CellFace.Y, digValue.CellFace.Z, digValue.Value, false, false);
			m_subsystemSoundMaterials.PlayImpactSound(cellValue, new Vector3(cellFace.X, cellFace.Y, cellFace.Z), 2f);
			m_componentMiner.DamageActiveTool(1);
			m_componentMiner.Poke(true);
		}

		public static bool IsDigable(int value, ref float rate, float quarryPower, float hackPower, float shovelPower)
		{
			int id = Terrain.ExtractContents(value);
			Block block1 = BlocksManager.Blocks[id];
			if (!block1.IsCollidable_(value))
				return false;
			float digResilience = block1.GetDigResilience(value);
			if (id == typeof(BedrockBlock).BlockIndex() || digResilience >= 15f)// float.PositiveInfinity)
				return false;
			BlockDigMethod blockDigMethod = block1.GetBlockDigMethod(value);
			switch (blockDigMethod)
			{
				case BlockDigMethod.Quarry:
					if (quarryPower > 1.5f)
					{
						rate = digResilience / quarryPower;
						return true;
					}
					break;
				case BlockDigMethod.Hack:
					if (hackPower > 1.5f)
					{
						rate = digResilience / hackPower;
						return true;
					}
					break;
				case BlockDigMethod.Shovel:
					if (shovelPower > 1.5f)
					{
						rate = digResilience / shovelPower;
						return true;
					}
					break;
			}
			return false;
		}
		public override void OnEntityRemoved()
		{
			if (m_eliteParticleSystem != null)
			{
				m_eliteParticleSystem.IsStopped = true;
				m_eliteParticleSystem = null;
			}
		}

		void UpdateNecro(float dt)
		{
			m_componentCreature.ComponentBody.TerrainCollidable = false;
			m_componentCreature.ComponentBody.BodyCollidable = false;
			m_componentChaseBehavior.IsActive = false;
			m_componentChaseBehavior.StopAttack();
			m_componentCreature.ComponentBody.Rotation = necro_rotation;
			necro_time += dt;
			if (necro_time >= 60f)
			{//超过时间消失
				Entity.FindComponent<ComponentSpawn>()?.Despawn();
			}
			var bodyPosition = m_componentCreature.ComponentBody.Position;
			if (necro_target != null && necro_target.IsAddedToProject && necro_target.ComponentHealth?.Health > 0f)
			{
				var targetPosition = necro_target.ComponentBody.BoundingBox.Center();
				Vector3 direction = Vector3.Normalize(targetPosition - bodyPosition);
				Vector2 direction2 = Vector2.Normalize((targetPosition - bodyPosition).XZ);
				if (necro_rotation == Quaternion.Identity)//初始化旋转，朝向玩家
					necro_rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitY, Vector2.Angle(direction2, -Vector2.UnitY));
				if (necro_direction == Vector2.Zero)//初始化方向，朝向玩家
					necro_direction = direction2;
				var flyOrder = new Vector3(necro_direction.X, 0f, necro_direction.Y);
				if (bodyPosition.Y < targetPosition.Y + 24f)//保持位置比攻击目标高
					flyOrder.Y = MathUtils.Max(flyOrder.Y, 1f);
				m_componentCreature.ComponentLocomotion.FlyOrder = flyOrder;

				if (m_fireCd <= 0f)
				{
					int skill = m_random.Int(1, 4);
					Vector3 right = Vector3.Normalize(Vector3.Cross(direction, Vector3.UnitY));
					Vector3 up = Vector3.Normalize(Vector3.Cross(direction, right));
					switch (skill)
					{
						case 1:
						{//投炸弹
							int count = m_random.Int(10, 15);
							for (int i = 0; i < count; i++)
							{
								Vector3 position = bodyPosition + new Vector3(m_random.Float(-3f, 3f), -1f, m_random.Float(-3f, 3f));
								if (i == 0)
									m_subsystemProjectiles.FireProjectile(BombBlock.Index, position, -Vector3.UnitY, Vector3.Zero, m_componentCreature);
								else
								{
									Time.QueueTimeDelayedExecution(Time.FrameStartTime + i * 0.1, () =>
									{
										int[] bombValues = [BombBlock.Index, IncendiaryBombBlock.Index, SmallGunpowderKegBlock.Index, SmallIncendiaryKegBlock.Index,
												DetonatorBlock.Index, Terrain.MakeBlockValue(ArrowBlock.Index, 0, ArrowBlock.SetArrowType(0, ArrowBlock.ArrowType.ExplosiveBolt))];
										int value = m_random.Bool(0.6f) ? SnowballBlock.Index : bombValues[m_random.Int(0, bombValues.Length - 1)];
										m_subsystemProjectiles.FireProjectile(value, position, -Vector3.UnitY, Vector3.Zero, m_componentCreature);
									});
								}
							}
							break;
						}
						case 2:
						{//放鳐鱼
							int count = m_random.Int(5, 8);
							for (int i = 0; i < count; i++)
							{
								Vector3 position = bodyPosition + new Vector3(m_random.Float(-3f, 3f), -1f, m_random.Float(-3f, 3f));
								Vector3 v3 = m_random.Float(-0.3f, 0.3f) * right
									+ m_random.Float(-0.3f, 0.3f) * up
									+ m_random.Float(-0.25f, 0.25f) * direction;
								Vector3 velocity = 60f * (direction + v3);
								int value = Terrain.MakeBlockValue(EggBlock.Index, 0, m_random.Bool(0.3f)
									? EggBlock.SetIsLaid(EggBlock.SetEggType(0, eggType_SAGhoul_Ray.EggTypeIndex), false)
									: EggBlock.SetIsCooked(0, true));
								Time.QueueTimeDelayedExecution(Time.FrameStartTime + i * 0.1, () =>
								{
									m_subsystemProjectiles.FireProjectile(value, position, velocity, Vector3.Zero, m_componentCreature);
								});
							}
							break;
						}
						case 3:
						{//放鸟
							int count = m_random.Int(5, 8);
							for (int i = 0; i < count; i++)
							{
								Vector3 position = bodyPosition + new Vector3(m_random.Float(-3f, 3f), -1f, m_random.Float(-3f, 3f));
								Vector3 v3 = m_random.Float(-0.3f, 0.3f) * right
									+ m_random.Float(-0.3f, 0.3f) * up
									+ m_random.Float(-0.25f, 0.25f) * direction;
								Vector3 velocity = 60f * (direction + v3);
								int value = Terrain.MakeBlockValue(EggBlock.Index, 0, m_random.Bool(0.7f)
									? EggBlock.SetIsLaid(EggBlock.SetEggType(0, eggType_SAGhoul_Bird.EggTypeIndex), false)
									: EggBlock.SetIsCooked(0, true));
								Time.QueueTimeDelayedExecution(Time.FrameStartTime + i * 0.1, () =>
								{
									m_subsystemProjectiles.FireProjectile(value, position, velocity, Vector3.Zero, m_componentCreature);
								});
							}
							break;
						}
						case 4:
						{//放灵魂
							int count = m_random.Int(4, 6);
							for (int i = 0; i < count; i++)
							{
								Vector3 position = bodyPosition + new Vector3(m_random.Float(-3f, 3f), -1f, m_random.Float(-3f, 3f));
								Time.QueueTimeDelayedExecution(Time.FrameStartTime + i * 0.25, () =>
								{
									SAGProjectile projectile = m_subsystemProjectiles.FireProjectile<SAGProjectile>(typeof(LargeSoulsResidueBlock).BlockIndex(), position, -Vector3.UnitY, m_random.Vector3(2f, 4f), m_componentCreature);
									if (projectile != null)
									{
										projectile.ProjectileStoppedAction = ProjectileStoppedAction.Disappear;
										projectile.TrailParticleSystem = new PukeTrailParticleSystem(10, 0.75f, float.MaxValue, Color.Purple);
										projectile.TrailOffset = Vector3.Zero;
										projectile.Target = m_componentChaseBehavior.Target;
									}
									m_subsystemAudio.PlayRandomSound("Audio/BossSkills/ParticleAttack", 2.5f, m_random.Float(-0.2f, 0.2f), position, SkillRange, 0f);
								});
							}
							break;
						}
					}
					m_fireCd = 5f;
				}
			}
			else
			{//没有目标时强制寻找最近的玩家
				float minDistanceSqr = float.MaxValue;
				ComponentPlayer nearestPlayer = null;
				foreach (var player in m_subsystemPlayers.ComponentPlayers)
				{
					if (!player.IsAddedToProject || player.ComponentHealth.Health <= 0f)
						continue;
					float distanceSqu = Vector2.DistanceSquared(player.ComponentBody.Position.XZ, m_componentCreature.ComponentBody.Position.XZ);
					if (distanceSqu < minDistanceSqr)
					{
						minDistanceSqr = distanceSqu;
						nearestPlayer = player;
					}
				}
				necro_target = nearestPlayer;
			}
		}
	}
}